package com.js.rtu.fragment.second;

import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;

import com.js.rtu.R;
import com.js.rtu.base.BaseFragment;
import com.js.rtu.config.CmdConfig;
import com.js.rtu.util.BleUtils;
import com.js.rtu.util.BluetoothUtils;
import com.js.rtu.util.CmdUtils;
import com.js.rtu.util.ToastUtil;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 23_17用户密码
 * 协议写33位，毛毛虫是32，以32为准
 * 33byte，1~32 位有效 APN（用‘A’ ~‘Z’ 、 ‘.’ 表示） ；下行和上行指令均以‘\0’ （00H） 为结束标志。
 * 非有效 APN 以’ \0’ 填充
 * Created by zwz on 2020/6/22.
 */
public class Cmd_23_17Fragment extends BaseFragment {


    @BindView(R.id.edt_input)
    EditText edtInput;



    public static Cmd_23_17Fragment newInstance() {
        Cmd_23_17Fragment fragment = new Cmd_23_17Fragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tab_second_cmd_23_17;
    }

    @Override
    protected void initView() {

    }






    private void set() {
        String data = edtInput.getText().toString();

            StringBuilder stringBuilder=new StringBuilder();
        for (int i = 0; i < data.length(); i++) {
            stringBuilder.append(BleUtils.strToASCII(data.substring(i,i+1)))
            .append(" ");
        }
        //1~24 位有效 APN
        if (data.length()!=32){
            for (int i = 0; i < 31 - data.length(); i++) {
                stringBuilder.append("00").append(" ");
            }
        }
        //00 为结束标志
        stringBuilder.append("00");
            String msg = CmdConfig.CMD_23_17 + " " + stringBuilder.toString();
            sendData(msg);

        Log.e("xxxxxxxx",msg);
    }

    private void sendData(String data) {
        String cmd = CmdUtils.getCmd(CmdConfig.CMD_23, data);

        BluetoothUtils.send(cmd, new BluetoothUtils.onCallback() {
            @Override
            public void onReceive(String msg) {
                dismissLoadingDialog();
                String[] data = msg.split(" ");
                if (data.length < 18) {
                    ToastUtil.info(msg);
                    return;
                }
                if (data[12].equals(CmdConfig.CMD_23)
                        && data[13].equals(CmdConfig.CMD_23_17)) {
                    if (data[14].equals(CmdConfig.SUCCECC)) {
                        ToastUtil.success("设置成功");
                    } else {
                        ToastUtil.error("设置失败");
                    }

                }


            }

            @Override
            public void onFail(String err) {
                toastShow(err);
                dismissLoadingDialog();
            }
        });
    }


    @OnClick(R.id.btn_set)
    public void onViewClicked() {
        set();
    }


}
